var pic_list = new Array();
var app = getApp()

const DB = wx.cloud.database({
  env: 'cloud1-2g7s81h60f3fd184'
}).collection("try_5-10")

let time = ""
let place = ""
let name = ""
let other = ""
var id = ''
let thing = ''
let result = ''
let remark = ''
// let moren_qest1 = ""
// let moren_qest2 = ""
// let moren_answer1 = ""
// let moren_answer2 = ""

let moren_lab1 = ""
let moren_lab2 = ""
let pic1 = ""
let pic2 = ""
let pic3 = ""
let lab = []

var call=""
var named=""
var award=""

var lost_placename = ""
var lost_place_latitude =""
var lost_place_longitude = ""
var category_lab_msg = ""
var store = ""
var state = ""
var losttime = ""
var altimg = ""



Page({
  data:{
    good:{},
    array: ['寻找中', '已找回'],
    array2: ['中饭','一教','图书馆'],
    losttime : "丢失物品时间",
    lost_placename : "丢失物品地点",
    category_lab_msg : "失物分类",
    alt_img:[],
    date:new Date(),
    judge:"",
    userInfo: {},
    hasUserInfo: false,
    showModel:false,
    showres:"不通过",
    passif:"",
    audit_state:[],
    options:[
      
    ] ,//选项列表

    options_qest:[

    ]//问题列表
  },



  
  //上传图片
  f0: function(event){
    let that = this;
    var that_ = this;

    wx.chooseImage({
      count: 3,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],

      success: function(res){
        console.log("选择成功",res)
        that_.setData({
          src:res.tempFilePaths[0],
          src_list:res.tempFilePaths,
          judge:res.tempFilePaths["length"]
          
         })
         that.pic_api(that.data.src_list[0])
         
        
        var src_list=res.tempFilePaths
        // var judge=res.tempFilePaths["length"]
        console.log("src_list",src_list)
        src_list.forEach((item,idx)=>{
          var fileName=Date.now()+"_"+idx;
          that.uploadImg(fileName,item)
        })


        },
        

        
      
    })
    
  },

  pic_api: function(e){    // 这里的imageData是图片转换成base64格式的数据
    var that = this;
    const detectUrl = `https://aip.baidubce.com/api/v1/solution/direct/imagerecognition/combination?access_token=${that.data.baiduToken}`    // baiduToken是已经获取的access_Token
    // console.log('123',detectUrl) 
      return new Promise(function(resolve,reject){        
      wx.request({            
        url: detectUrl,            
        data: {                
          image: e,
          scenes:["advanced_general","multi_object_detect"],
                    
        },            
        method: 'POST',            
        dataType: 'json',            
        header:{                
          'content-type': 'application/json'    // 必须的        
        },            
        success: function(res, resolve){              
          console.log('调用图像识别APIsuccess：',res.data);              
          // var word = res.data.words_result[0].words              	
          // console.log(word);            
        },            
        fail : function(res,reject){              
          console.log('调用图像识别APIfail：',res.data);           			},            
  
      })
    }) 
  },




//上传图片到云开发
uploadImg(fileUrl,path){
  wx.cloud.uploadFile({
    cloudPath: fileUrl+'example.png', // 上传至云端的路径
    filePath: path, // 小程序临时文件路径
    success: res => {
      // 返回文件 ID
      pic_list.push(res.fileID)
      console.log("上传成功",res)
      console.log("照片列表",pic_list)
      pic_list.forEach((item,idx)=>{
        var pic_idx = pic_list[idx]
        console.log("数组元素",pic_idx)
      })
      
      // pic_list.append(res.fileID)
      // console.log(cloundPath)
      // pic=res.fileID
      // console.log("pic",res.fileID)
      this.setData({
        pic: res.fileID
      })
      
    },
    fail: console.error
  })



},



//点击预览图片
  f1:function(event){
    // var that_=this;
    // var src = event.currentTarget.dataset.src;//获取data-src
    // var imgList = that_.data.imgUrls;//获取data-list
    wx.previewImage({
      
      current: pic_list[0], // 当前显示图片的http链接
      urls: pic_list, // 需要预览的图片http链接列表
      success:function(res){
        console.log("1111",res)
      }
    })
  },


// 动态变化标签
//添加选项
addOption(e){
  let options = this.data.options
  console.log(options)
  options.push({value:''})
  console.log(options.length)
  var len = options.length
  if(len<=3){
    this.setData({
        options: options
      })
  }
  

},
//文本输入
bindinput(e){
  console.log(e)
  let index = e.currentTarget.dataset.id //索引位置
  let value = e.detail.value //输入的内容
  let options = this.data.options
  options[index].value = value
//   for(var i =0;i<index;i++){
//     arr.push(lab[options[i].value]);
 
// };
  this.setData({
    options: options,
    lab:{}
  })
},
//删除选项
delOption(e){
  let index = e.currentTarget.dataset.id //索引位置
  let options = this.data.options
  options.splice(index,1)

  this.setData({
    options: options
  })

},

// 动态变化问题表单
//添加选项
addOption_qest(e){
  let options_qest = this.data.options_qest
  console.log(options_qest)
  options_qest.push({value:''})
  console.log(options_qest.length)
  var len_qest = options_qest.length
  if(len_qest<=3){
    this.setData({
        options_qest: options_qest
      })
  }
  

  
},
//文本输入
bindinput_qest1(e){
  console.log(e)
  let index_qest1 = e.currentTarget.dataset.id //索引位置
  let value_qest1 = e.detail.value //输入的内容
  let options_qest1 = this.data.options_qest1
  options_qest1[index_qest1].value = value_qest1
  this.setData({
    options_qest1: options_qest1
  })
},

bindinput_qest2(e){
  console.log(e)
  let index_qest2 = e.currentTarget.dataset.id //索引位置
  let value_qest2 = e.detail.value //输入的内容
  let options_qest2 = this.data.options_qest2
  options_qest2[index_qest2].value = value_qest2
  this.setData({
    options_qest2: options_qest2
  })
},
//删除选项
delOption_qest(e){
  let index_qest = e.currentTarget.dataset.id //索引位置
  let options_qest = this.data.options_qest
  options_qest.splice(index_qest,1)

  this.setData({
    options_qest: options_qest
  })

},



onLoad(option) {
  store = this.data.array[0]
  this.setData({
    index:0,
  })
  // console.log("物品信息",this.data.good.award)
  time = this.data.good.time
  award = this.data.good.award
  call = this.data.good.call
  lost_place_latitude = this.data.good.lost_place_latitude
  lost_place_longitude = this.data.good.lost_place_longitude
  lost_placename = this.data.good.lost_placename
  moren_lab1 = this.data.good.moren_lab1
  moren_lab2 = this.data.good.moren_lab2
  name = this.data.good.name
  other = this.data.good.other
  place = this.data.good.place
  named = this.data.good.named
  state = this.data.good.state
  losttime = this.data.good.losttime
  altimg = this.data.good.pic1
  // console.log("原始图",altimg)
  // this.setData({
  //   alt_img:altimg
  // })

  console.log('psonal传值',option.id)
  id = option.id
  this.getDetail()
	var apiKey = 'G5gM9POiPmwhszXhP8Yfq5UG';    
	var secKey = '5Qz7ICxTRzEr53hgj5nhatpdLLvZd31y';    
	var tokenUrl = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${apiKey}&client_secret=${secKey}`;    
	var that = this; 
	wx.request({        
		url: tokenUrl,        
		method: 'POST',        
		dataType: 'json',        
		header:{            
			'content-type': 'application/json; charset-UTF-8'        
		},        
		success: function(res){            
			console.log("[BaiduToken获取成功]",res);            
			that.setData({                
				baiduToken: res.data.access_token  })        
		},        
		fail: function(res){            
			console.log("[BaiduToken获取失败]",res);
		}    
  })
  
  var user = wx.getStorageSync('user');
    if(user) {
      console.log('用户信息已授权')
      this.setData({
        hasUserInfo:true,
        userInfo: user,
      })
    }
},

getDetail() {
  wx.cloud.database().collection('try_5-10')
    .doc(id)
    .get()
    .then(res => {
      console.log('物品查询成功',res)
      this.setData({
        good:res.data,
        alt_img:res.data.pic1,
        audit_state:res.data.audit,
        passif:res.data.audit_res
      })
      console.log("状态",this.data.audit_state)
    })
    .catch(res => {
      console.error('物品查询失败',res)
    })
},

//获取用户输入的信息
time(event){
  console.log(event.detail.value)
  time = event.detail.value
},
place(event){
  var that = this
    wx.chooseLocation({
      success(res) {
        console.log(res.name);
        lost_placename = res.name
        lost_place_latitude = res.latitude
        lost_place_longitude = res.longitude

        that.setData({
          lost_placename:lost_placename,
          losttime:getApp().globalData.globalData_lost_time
        })
      },
    })
  // console.log(event.detail.value)
  // place = event.detail.value
},

name(event){
  console.log(event.detail.value)
  name = event.detail.value
},

category(e){
  var that = this
  wx.navigateTo({
    url: '../../pages/category_add/category_add',
  })
},


moren_qest1(event){
  console.log(event.detail.value)
  moren_qest1 = event.detail.value
},
moren_qest2(event){
  console.log(event.detail.value)
  moren_qest2 = event.detail.value
},
moren_answer1(event){
  console.log(event.detail.value)
  moren_answer1 = event.detail.value
},
moren_answer2(event){
  console.log(event.detail.value)
  moren_answer1 = event.detail.value
},
morenlab1(event){
  console.log(event.detail.value)
  moren_lab1 = event.detail.value
},
morenlab2(event){
  console.log(event.detail.value)
  moren_lab2 = event.detail.value
},
other(event){
  console.log(event.detail.value)
  other = event.detail.value
},

award(event){
  console.log(event.detail.value)
   award = event.detail.value
},
named(event){
  console.log(event.detail.value)
   named = event.detail.value
},
call(event){
  console.log(event.detail.value)
   call = event.detail.value
},
refuse(event){
  console.log(event.detail.value)
  remark = event.detail.value
},

bindPickerChange: function (e) {
  var that = this;
  console.log('picker发送选择改变，携带值为', e.detail.value)
  store = that.data.array[e.detail.value]
  console.log('store值为', store)
  this.setData({
    index:e.detail.value
  })
},

bindPicker2: function (e) {
  var that = this;
  console.log('picker发送选择改变，携带值为', e.detail.value)
  store = that.data.array2[e.detail.value]
  console.log('store值为', store)
  this.setData({
    index:e.detail.value
  })
},

//修改数据
upData:function(e){
  console.log("losttime",getApp().globalData.globalData_lost_time)
  wx.showModal({
    title:"提示",
    content:"是否确认修改信息",
    success:(res)=> {
      console.log(res)
      if (res.confirm) {
        var that = this
        that.updata_func()
      }
      else if (res.cancel) {
        console.log("取消",)
      }
    }
  })
},

//修改数据
updata_func() {
  wx.cloud.database().collection('try_5-10')
  .doc(id)
  .update({
          data:{
            time:time,
            place:place,
            name:name, 
            other:other,
            moren_lab1:moren_lab1,
            moren_lab2:moren_lab2,   
            pic1:pic_list[0],
            // pic2:pic_list[1],
            // pic3:pic_list[3],
           lost_placename:lost_placename,
           lost_place_latitude:lost_place_latitude,
           lost_place_longitude:lost_place_longitude,
          losttime : getApp().globalData.globalData_lost_time,
          category_lab_msg:getApp().globalData.globalData_category_value,
           call:call,
           named:named,
           award:award,
            state:store,
          },
          success(res){
            console.log("添加成功",res)
            wx.showToast({
              title: '提交成功',
              icon: 'success',
              duration: 2000
            })
            wx.navigateBack({
              url:'/pages/psonal_rec/psonal_rec?id=' + id
            })
          },
          fail(res){
            console.log("添加失败",res)
            wx.showToast({
              title: '提交失败',
              icon: 'error',
              duration: 2000
              })
          },
        })
},

//修改审核
change_s2() {
  wx.showModal({
    title:"提示",
    content:"是否审核该物品为通过",
    success(res) {
      console.log(res)
      if (res.confirm) {
        DB.doc(id).update({
          data:{
            audit_res:"通过"
          }
        })
        .then(res=>{
          console.log("修改成功",res)
          wx.navigateBack({
            url:'/pages/check/check'
          })
        })
        .catch(err =>{
          console.log("修改失败",err)
        })
      }
    }
  })
},

change_s1() {
  wx.showModal({
    title:"提示",
    content:"是否撤销该物品审核通过",
    success(res) {
      console.log(res)
      if (res.confirm) {
        DB.doc(id).update({
          data:{
            audit_res:"不通过"
          }
        })
        .then(res=>{
          console.log("修改成功",res)
          wx.navigateBack({
            url:'/pages/check/check'
          })
        })
        .catch(err =>{
          console.log("修改失败",err)
        })
      }
    }
  })
},

alter_pic() {
  console.log("图片",this.data.alt_img)
  let cloud_img = this.data.alt_img
  wx.cloud.deleteFile({
    fileList: [cloud_img],
    success: res => {
      // handle success
      console.log(res.fileList)
    },
    fail: console.error
  })
},

get_Profile() {
  var that = this
  wx.getUserProfile({
    lang:'zh_CN',
    desc: '用于完善会员资料', 
    success: (res) => {
      console.log("用户信息",res)
      if (!that.hasUserInfo && res.userInfo) {
        wx.showToast({
          title: '授权成功',
          success:function() {
            setTimeout(function() {
              that.setData({
                showModel:true
              })
            },800)
          }
        })
        wx.setStorageSync('user',res.userInfo)
        that.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    }
  })
},

sendOne() {
  if (remark==null || remark==''){
    wx.showToast({
      icon:'none',
      title: '还有选项没有输入',
    })
    return
  }
  wx.cloud.callFunction({
    name: "shenhe",
    data: {
      openid:this.data.good._openid,
      result:this.data.showres,
      name:this.data.good.name,
      remark:remark
    }
  }).then(res => {
    console.log("发送成功",res.result.errMsg)
    console.log("测试",this.data.good._openid)
    wx.showToast({
      title: '发送成功',
      duration:2000,
    })
    DB.doc(id).update({
      data:{
        audit:true
      }
    })
    .then(res=>{
      console.log("审核完成",res)
      this.setData({
        showModel:false
      })
      wx.navigateback({
        url: '/pages/check/check',
      })
    })
    .catch(err=>{
      console.log("audit修改失败",err)
    })
  }).catch(err => {
    console.log("发送失败",err)
  })
},

onCancel() {
  this.setData({
    showModel:false
  })
},

approve() {
  wx.showToast({
    title: '审核通过',
    icon: 'success',
    duration: 1000
  })
  DB.doc(id).update({
    data:{
      audit:true,
      audit_res:"通过"
    }
  }).then(res=>{
    console.log("审核完成：通过",res)
    this.setData({
      showModel:false
    })
    wx.redirectTo({
      url: '/pages/check/check',
    })
  }).catch(err=>{
    console.log('审核失败',err)
  })
}

})

